04. Creating Variables from Struct Properties

If we want, we can create a variable and assign it a value from a struct property.

For example, let’s create a variable called collegeAged and set it equal to ayush.age. This means the collegeAged variable is an Int just like the age property.

The variable "collegeAged" takes on the value and type of "ayush.age".

The variable "collegeAged" takes on the value and type of "ayush.age".

We can do another. Let's create a variable called anotherSchool and set it equal to ayush.school. Now anotherSchool is a String variable and it equals USC.

The variable "anotherSchool" takes on the value of "ayush.school".

The variable "anotherSchool" takes on the value of "ayush.school".

Accessing Properties

And that’s it! Accessing the properties of structs is as simple as typing a dot after the instance name followed by the name of the property. And Xcode and the Swift compiler work together to even suggest the property names for us as we type. How convenient!

After typing the dot operator, Xcode suggests property names for us.

After typing the dot operator, Xcode suggests property names for us.

Structs on Structs on Structs

Why Are Structs Useful?

QUESTION:

Why are structs useful? And, can you give an example of when you would want to use one?

ANSWER:

Structs are useful because they allow us to bind-up multiple types into one easy-to-use type. One situation where you might want to use a struct is to encapsulate all the properties associated with a video game. Imagine you have an app that lets you search for a video game by bar code, and then displays the game’s information.

struct VideoGame {
    let name: String
    let barCode: String
    let description: String
}

You could have a VideoGame struct that contains properties for name, bar code, and anything else you may need.